package com.fresh.liangyi.config;

import com.fresh.liangyi.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    //UserDetails控制用户访问
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //设置security密码编码器
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        //        基于UserDetailService自定义身份认证
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(encoder);
    }

    //控制用户权限
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //访问url控制
        http.authorizeRequests()
                //配置涉及用户权限界面url
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/customer/**").hasAnyRole("customer")
                .antMatchers("/business/**").hasAnyRole("business")
                //放行静态资源文件夹
                .antMatchers("/back/**","/assets/**","/user/**","/article_img/**","/image/**").permitAll()
                //放行普通访问的url
                .antMatchers("/","/page/**","/article/**","/login/**","/goods/**","/order/**","/register/**","/menu/**").permitAll()
                .anyRequest().authenticated();

        //使用自定义登录界面URL
        http.formLogin()
                .loginPage("/login").permitAll()
                //usernameParameter对应登录页面表单中用户名控件，password则对应密码控件。（具体内容需要根据登录页面确定）
                .usernameParameter("username").passwordParameter("password")
                .defaultSuccessUrl("/")
                .failureUrl("/login?error");
        http.rememberMe()
                .rememberMeParameter("rememberme").tokenValiditySeconds(60*60*24);//设置token有效期为1天

        //退出账户
        http.logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/");

        //记住我
        http.rememberMe()
                //使用简单加密token
                .rememberMeParameter("rememberme").tokenValiditySeconds(200); //前端name为remember单选框控件，有效期为200秒
        //使用持久化token
//                .tokenRepository()

//        关闭csrf防护
        http.csrf()
                .disable();
    }
}
